import {
  createSlice,
  createAsyncThunk,
  createEntityAdapter,
  createSelector
} from '@reduxjs/toolkit'
import axios from 'axios'

const todosAdapter = createEntityAdapter()

const { selectAll } = todosAdapter.getSelectors()

// 创建执行异步操作的 Action
// export const loadTodos = createAsyncThunk(
//   'todos/loadTodos',
//   (payload, { dispatch }) => {
//     axios.get(payload).then(response => dispatch(setTodos(response.data)))
//   }
// )
export const loadTodos = createAsyncThunk('todos/loadTodos', payload =>
  axios.get(payload).then(response => response.data)
)

export const TODOS_FEATURE_KEY = 'todos'

export const selectTodosList = createSelector(
  state => state[TODOS_FEATURE_KEY],
  selectAll
)

const { reducer: TodosReducer, actions } = createSlice({
  name: TODOS_FEATURE_KEY,
  initialState: todosAdapter.getInitialState(),
  reducers: {
    // addTodo: (state, action) => {
    //   // state.push(action.payload)
    //   todosAdapter.addOne(state, action.payload)
    // },
    addTodo: todosAdapter.addOne,
    // setTodos: (state, action) => {
    //   // action.payload.forEach(todo => state.push(todo))
    //   todosAdapter.addMany(state, action.payload)
    // }
    setTodos: todosAdapter.addMany
  },
  // 接收执行异步操作的Action
  extraReducers: {
    // pending
    // rejected
    // fulfilled
    // [loadTodos.fulfilled]: (state, action) => {
    //   // action.payload.forEach(todo => state.push(todo))
    //   todosAdapter.addMany(state, action.payload)
    // }
    [loadTodos.fulfilled]: todosAdapter.addMany
  }
})

export const { addTodo, setTodos } = actions
export default TodosReducer
